﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Sirenix.OdinInspector;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities;
using UnityEditor;
using UnityEngine;

namespace BearUtil
{
    [GlobalConfig("StoryEditor/Nodes/Actor")]
    public class ActorsOverview : GlobalConfig<ActorsOverview>, ICustomSetting
    {
        [TableList(AlwaysExpanded = true, DrawScrollView = false)]
        public List<ActorData> actors;

        private const string actorPath = "Assets/StoryEditor/Actor/Data/";
        public string AddName
        {
            get
            {
                return "添加新人物";
            }
            set { }
        }
        public string RemoveName 
        {
            get
            {
                return "清空数据";
            }
            set{}
        }

        public void Add(OdinMenuEditorWindow window)
        {
            if (actors == null) actors = new List<ActorData>();

            var actor = ScriptableObject.CreateInstance<ActorData>();
            if (!Directory.Exists(actorPath))
            {
                Directory.CreateDirectory(actorPath);
                AssetDatabase.Refresh();
            }
            
            var dest = EditorUtility.SaveFilePanel("Save File", actorPath, 
                "Name " + typeof(ActorData).GetNiceName(), "asset");
            
            if (!string.IsNullOrEmpty(dest) &&
                PathUtilities.TryMakeRelative(
                    Path.GetDirectoryName(Application.dataPath),
                    dest, out dest))
            {
                AssetDatabase.CreateAsset(actor, dest);
                AssetDatabase.Refresh();
                
                actors.Add(actor);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(actor);
            }
        }
        
        public void Remove(OdinMenuItem selected)
        {
            for (int i = 0; i < actors.Count; i++)
            {
                actors[i].DeleteSelf();
            }
        }


        /// <summary>
        /// 清空已丢失数据
        /// </summary>
        public void ClearNull()
        {
            for (int i = 0; i < actors.Count; i++)
            {
                if (actors[i] == null)
                {
                    actors.RemoveAt(i);
                    i--;
                }
            }
        }
        

        // Voice 
        public List<string> VoiceTypes;
    }   
}
